package com.galcier.jdbc.service.impl;

import com.galcier.jdbc.po.UserPO;
import com.galcier.jdbc.service.UserService;

import javax.sql.DataSource;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * date 2023-12-15 13:32
 *
 * @author glacier
 * @version 1.0
 */
public class UserServiceImpl implements UserService {

    private final DataSource dataSource;

    public UserServiceImpl(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public List<UserPO> findByUsername(String username) {
        List<UserPO> users = new ArrayList<>();
        // 定义sql语句 ?表示占位符
        String sql = "select * from sys_user a where a.username = ?";
        try (
                // 获取连接
                Connection connection = dataSource.getConnection();
                // 获取预编译对象
                PreparedStatement preparedStatement = getPreparedStatement(connection, sql, username);
                // 执行查询
                ResultSet resultSet = preparedStatement.executeQuery()
        ) {
            System.out.println(resultSet.getMetaData());
            while (resultSet.next()) {
                UserPO item = new UserPO();
                item.setId(resultSet.getLong("id"));
                item.setUsername(resultSet.getString("username"));
                item.setPassword(resultSet.getString("password"));
                item.setNickname(resultSet.getString("nickname"));
                item.setCreateTime(resultSet.getObject("create_time", LocalDateTime.class));
                users.add(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }


    @Override
    public int insert(UserPO user) {
        return 0;
    }

    @Override
    public int update(UserPO user) {
        return 0;
    }

    @Override
    public int delete(Long id) {
        return 0;
    }

    /**
     * 获取预编译对象
     *
     * @param connection 连接
     * @param sql        sql语句
     * @param params     参数
     * @return 预编译对象
     * @throws SQLException sql异常
     */
    private PreparedStatement getPreparedStatement(final Connection connection, final String sql, final Object... params) throws SQLException {
        // 获取预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null && params.length > 0) {
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
        }
        return preparedStatement;
    }
}
